package com.qwz.example;

import com.qwz.common.TestDb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**  
* @Description: 安全管理，实现成单例
* @Package com.qwz.example.SecurityMgr
* @author Qiuwuzhi
* @date 2019/12/23 16:53
* @version V1.0
*/
public class SecurityMgr {

    private SecurityMgr() {
    }

    private static SecurityMgr securityMgr = new SecurityMgr();

    public static SecurityMgr getInstance() {
        return securityMgr;
    }

    /**
     * 在运行期间，用来存放登录人员对应的权限
     */
    private Map<String, Collection<FlyWeight>> map = new HashMap<String, Collection<FlyWeight>>();

    /**
     * 模拟登录的功能
     * @param user
     */
    public void login(String user) {
        //登录时就把需要把该用户所拥有的权限，从数据库中取出来，放到缓存中
        Collection<FlyWeight> collection = queryByUser(user);
        map.put(user, collection);
    }

    /**
     * 从数据库中获取某人所拥有的权限
     * @param user
     * @return
     */
    private Collection<FlyWeight> queryByUser(String user) {
        Collection<FlyWeight> collection = new ArrayList<FlyWeight>();
        for (String s : TestDb.collectionDb) {
            String[] ss = s.split(",");
            if (ss[0].equals(user)) {
                FlyWeight fm = FlyWeightFactory.getInstance().getFlyWeight(ss[1] + "," + ss[2]);
                //
                collection.add(fm);

            }
        } return collection;

    }

    /**
     * 判断某用户对某个安全体是否拥有某种权限
     * @param user
     * @param securityEntity
     * @param permit
     * @return
     */
    public boolean hasPermit(String user, String securityEntity, String permit) {
        Collection<FlyWeight> collection = map.get(user);

        if (collection == null || collection.size() == 0) {
            System.out.println(user + "没有登陆或是没有分配任务权限");
            return false;
        }

        for (FlyWeight flyWeight : collection) {
            System.out.println(""+flyWeight);
            if (flyWeight.match(securityEntity, permit)) {
                return true;
            }
        }
        return false;
    }
}
